import 'package:demo/util/asset.dart';
import 'package:flutter/material.dart';
import '../Tabs.dart';
import 'spend.dart';
import 'income.dart';
import 'dart:convert';

class AddPage extends StatefulWidget {
  @override
  _AddPageState createState() => _AddPageState();
}

class _AddPageState extends State<AddPage> {
  var myData, money, time, type;
  var rollOut = '现金';
  var into = '现金';
  String select;
  String remark = '';

  // 保存信息逻辑
  void getData() {
    myData = jsonDecode(SpUtil.preferences.getString('myData'));
    money = int.parse(SpUtil.preferences.getString('money'));
    select = SpUtil.preferences.getString('select');
    remark = SpUtil.preferences.getString('remark');
    time = int.parse(SpUtil.preferences.getString('time'));
    type = SpUtil.preferences.getString('type');

    var currentTime = DateTime.fromMillisecondsSinceEpoch(time);
    var year = currentTime.year;
    var month = currentTime.month;
    var day = currentTime.day;
    var typeKey = '';
    if (type == '支出') {
      typeKey = 'sumSpend';
    } else if (type == '收入') {
      typeKey = 'sumIncome';
    } else if (type == '转账') {
      typeKey = 'sumRoll';
      rollOut = SpUtil.preferences.getString('rollOut');
      into = SpUtil.preferences.getString('into');
    }

    bool yearFlag = false;
    bool monthFlag = false;
    bool dayFlag = false;
    var dayDetail = {
      'select': select,
      'type': type,
      'time': time,
      'remark': remark,
      'rollOut': rollOut, // 转账——转出
      'into': into, // 转账——转入
      'sumIncome': 0, // 总收入
      'sumSpend': 0 // 总支出
    };
    dayDetail[typeKey] = money;
    var dayObj = {
      "time": day,
      "sumIncome": 0,
      "sumSpend": 0,
      'dayDetail': [dayDetail]
    };
    var monObj = {"month": month, "sumIncome": 0, "sumSpend": 0, 'dayList': []};
    var yearObj = {
      "year": year,
      "sumIncome": 0,
      "sumSpend": 0,
      'monthList': []
    };
    for (var item in myData) {
      if (year == item['year']) {
        yearFlag = true;
        item[typeKey] += money;
        for (var monthItem in item['monthList']) {
          if (month == monthItem['month']) {
            monthFlag = true;
            monthItem[typeKey] += money;
            for (var dayItem in monthItem['dayList']) {
              if (day == dayItem['time']) {
                dayFlag = true;
                dayItem[typeKey] += money;
                var obj = {
                  'select': select,
                  'type': type,
                  'time': time,
                  'remark': remark,
                  'rollOut': rollOut, // 转账——转出
                  'into': into, // 转账——转入
                  'sumIncome': 0, // 总收入
                  'sumSpend': 0, // 总支出
                  'sumRoll': 0 // 总转账
                };
                obj[typeKey] = money;
                dayItem['dayDetail'].add(obj);
                break;
              }
            }
            if (!dayFlag) {
              dayObj[typeKey] = money;
              monthItem['dayList'].add(dayObj);
            }
            break;
          }
        }
        if (!monthFlag) {
          dayObj[typeKey] = money;
          monObj['dayList'] = [dayObj];
          monObj[typeKey] = money;
          item['monthList'].add(monObj);
        }
        break;
      }
    }
    if (!yearFlag) {
      dayObj[typeKey] = money;
      monObj['dayList'] = [dayObj];
      monObj[typeKey] = money;
      yearObj['monthList'] = [monObj];
      yearObj[typeKey] = money;
      myData.add(yearObj);
    }
    SpUtil.preferences.setString(
      'time',
      DateTime.now().millisecondsSinceEpoch.toString(),
    );
    SpUtil.preferences.setString('myData', jsonEncode(myData));
    // Navigator.pop(context, '回传');
    // 跳转并清空路由栈
    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(
      builder: (context) {
        return Tabs();
      },
    ), (Route<dynamic> route) => false);
  }

  // 保存信息方法
  void _saveAdd() {
    getData();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: Text('记一笔'),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.done),
              onPressed: _saveAdd,
            ),
          ],
          bottom: TabBar(
            tabs: <Widget>[
              Tab(
                text: '支出',
              ),
              Tab(
                text: '收入',
              ),
            ],
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            SpendCom(),
            IncomeCom(),
          ],
        ),
      ),
    );
  }
}
